package org.springblade.modules.teambition.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Component
public class HttpUtil<T> {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

//    @Resource
//    private RestTemplate restTemplate;

    private static final List<Charset> UTF8 = Collections.singletonList(StandardCharsets.UTF_8);

    public static  <T> T doPostJson(String json, String url, ParameterizedTypeReference<T> responseBodyType, String token, String orgId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setAcceptCharset(UTF8);
        headers.setContentType(MediaType.APPLICATION_JSON);
		headers.set("Authorization", "Bearer " + token);
        //X-Tenant-Id
		headers.set("X-Tenant-Id",orgId);
		headers.set("X-Tenant-Type","organization");
        HttpEntity<String> httpEntity = new HttpEntity<>(json, headers);
        logger.info("request json {}", json);
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<T> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, responseBodyType);
        T body = exchange.getBody();
        logger.info("return {}", body);
        return body;
    }


	public static  <T> T doGet(Map<String,Object> uriVariables, String url, ParameterizedTypeReference<T> responseBodyType, String token, String orgId) {
		UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(url);
		uriVariables.forEach(uriComponentsBuilder::queryParam);
		String s = uriComponentsBuilder.toUriString();
		return doGet(s,responseBodyType,token,orgId);
	}


	public static  <T> T doGet( String url, ParameterizedTypeReference<T> responseBodyType, String token, String orgId) {
		HttpHeaders headers = new HttpHeaders();
		headers.set("Authorization", "Bearer " + token);
		//X-Tenant-Id
		headers.set("X-Tenant-Id", orgId);
		headers.set("X-Tenant-Type", "organization");
		HttpEntity<Object> httpEntity = new HttpEntity<>( headers);
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<T> exchange = restTemplate.exchange(
			url,
			HttpMethod.GET,
			httpEntity,
			responseBodyType);// 这里指定响
		T body = exchange.getBody();
		return body;
	}

}
